var express = require('express');
var router = express.Router();
let { userModel, menuModel } = require('../db/model')
let jwt = require('express-jwt');
let jsonwebtoken = require('jsonwebtoken');
var fs=require('fs')
// 导入multiparty模块
var multiparty=require('multiparty');
var path=require('path')

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});
// 登录
router.post('/login', async (req, res, next) => {
  let con = req.body
  let user = await userModel.findOne(con)
  if (user) {
    let token = jsonwebtoken.sign({ _id: user._id }, 'flag', { expiresIn: '1d' })
    res.send({
      code: 200,
      message: "登陆成功",
      token: token
    })
  } else {
    res.send({
      code: 101,
      message: "账号或密码错误"
    })
  }
})
// 退出登录
router.post('/logout', (req, res, next) => {
  res.send({
    code: 200,
    message: '退出成功'
  })
})
// 获取个人信息
router.get('/info', async (req, res, next) => {
  let info = ''
  if (req.user_id) {
    info = await userModel.findOne({ _id: req.user_id })
  } else {
    info = await userModel.findOne({ _id: '63b2862aae8264c68c033e1c' })
  }
  res.send({
    code: 200,
    message: "信息返回成功",
    info
  })
})
// 获取菜单列表
router.get('/menu', async (req, res, next) => {
  let menu = await menuModel.find({});
  let data = await menuModel.aggregate([
    {
      $match: {
        pid: null
      }
    },
    {
      $lookup: {
        from: 'menu',
        localField: '_id',
        foreignField: 'pid',
        as: 'children'
      }
    }
  ])
  for (const item of data) {
    item.id = item._id
    for (const ite of item.children) {
      ite.id = ite._id
      let list = []
      for (const i of menu) {
        if (ite._id.equals(i.pid)) {
          i.id = i._id
          list.push(i)
        }
      }
      ite.children = list
    }
  }
  for(const i of data[0].children){
    if (i.children.length === 0) {
      delete i.children
    }
  }
  // console.log(data[0].children);
  res.send({
    code: 200,
    message: "信息返回成功",
    data
  })
})
// 上传文件
router.post('/uploadfile',(req,res)=>{
//创建一个multiparty类型的表单对象
  let form=new multiparty.Form()
//设置提交的路径,upload目录不会自动创建，需要手动创建
  form.uploadDir='public/upload'
  form.parse(req,(err,data,fileds)=>{
    console.log(fileds.avatar[0].path);
    res.send({
      code:200,
      imgs:path.basename(fileds.avatar[0].path)
    })
  })
})

module.exports = router;
